'use client';

import React, { useState, useEffect } from 'react';
import Button from '@/components/ui/Button';
import { 
  GitBranch, 
  Brain, 
  Database, 
  Settings,
  Play,
  CheckCircle,
  AlertCircle,
  BarChart3,
  Users,
  ArrowRight,
  Cloud,
  Wifi,
  Monitor,
  Cpu,
  Clock,
  Activity,
  Server,
  Zap,
  Plus,
  TrendingUp
} from 'lucide-react';

export default function CollaborationPage() {
  const [selectedMethod, setSelectedMethod] = useState('knowledge_distillation');
  const [selectedNodes, setSelectedNodes] = useState<string[]>([]);
  const [selectedDatasets, setSelectedDatasets] = useState<string[]>([]);
  const [selectedScenario, setSelectedScenario] = useState('');
  const [selectedDatasetType, setSelectedDatasetType] = useState('');
  const [isCalculating, setIsCalculating] = useState(false);
  const [estimationResults, setEstimationResults] = useState<any>(null);
  const [taskStarted, setTaskStarted] = useState(false);

  // 云边节点数据 - 模拟从API获取
  const [cloudNodes, setCloudNodes] = useState([
    {
      id: 'cloud-1',
      name: '云端节点 1',
      location: '北京',
      status: 'online',
      cpu: '32 核',
      memory: '128GB',
      gpu: 'A100 x4',
      bandwidth: '10Gbps'
    },
    {
      id: 'cloud-2',
      name: '云端节点 2',
      location: '上海',
      status: 'online',
      cpu: '64 核',
      memory: '256GB',
      gpu: 'A100 x8',
      bandwidth: '10Gbps'
    },
    {
      id: 'cloud-3',
      name: '云端节点 3',
      location: '深圳',
      status: 'online',
      cpu: '48 核',
      memory: '192GB',
      gpu: 'A100 x6',
      bandwidth: '10Gbps'
    }
  ]);

  const [edgeNodes, setEdgeNodes] = useState([
    {
      id: 'edge-1',
      name: '边缘节点 1',
      location: '深圳',
      status: 'online',
      cpu: '16 核',
      memory: '64GB',
      gpu: 'V100 x2',
      bandwidth: '1Gbps'
    },
    {
      id: 'edge-2',
      name: '边缘节点 2',
      location: '广州',
      status: 'online',
      cpu: '16 核',
      memory: '64GB',
      gpu: 'V100 x2',
      bandwidth: '1Gbps'
    },
    {
      id: 'edge-3',
      name: '边缘节点 3',
      location: '杭州',
      status: 'busy',
      cpu: '8 核',
      memory: '32GB',
      gpu: 'T4 x1',
      bandwidth: '500Mbps'
    },
    {
      id: 'edge-4',
      name: '边缘节点 4',
      location: '成都',
      status: 'online',
      cpu: '12 核',
      memory: '48GB',
      gpu: 'T4 x2',
      bandwidth: '800Mbps'
    },
    {
      id: 'edge-5',
      name: '边缘节点 5',
      location: '西安',
      status: 'offline',
      cpu: '8 核',
      memory: '32GB',
      gpu: 'T4 x1',
      bandwidth: '500Mbps'
    }
  ]);

  // 电力场景数据集数据 - 模拟从API获取
  const [powerScenarios] = useState([
    {
      id: 'personnel-operation',
      name: '人员作业',
      description: '电力人员作业安全监控相关数据集'
    },
    {
      id: 'equipment-defects',
      name: '设备表观缺陷',
      description: '电力设备外观缺陷检测数据集'
    },
    {
      id: 'environmental-hazards',
      name: '环境隐患',
      description: '电力环境安全隐患识别数据集'
    },
    {
      id: 'equipment-maintenance',
      name: '设备故障运检',
      description: '设备故障诊断与运维检修数据集'
    }
  ]);

  const [datasetTypes] = useState([
    { id: 'base', name: '基础数据集', description: '场景的核心训练数据' },
    { id: 'incremental', name: '增量数据集', description: '用于增量学习的新数据' },
    { id: 'forgetting', name: '遗忘评估数据集', description: '用于评估模型遗忘程度' },
    { id: 'quantization', name: '量化校准数据集', description: '用于模型量化校准' }
  ]);

  const [datasetsData] = useState({
    'personnel-operation': {
      'base': [
        {
          id: 'po-base-001',
          name: '高压作业人员监控基础数据',
          uploader: '安监中心A',
          isLearned: true,
          dataSize: '3.2GB',
          uploadTime: '2024-01-15 09:30:00',
          isAnnotated: true,
          dataFormat: 'VIDEO',
          sampleCount: 156000,
          timeRange: '2020-2023年',
          updateFrequency: '每日'
        },
        {
          id: 'po-base-002',
          name: '配电作业安全行为数据集',
          uploader: '供电局B',
          isLearned: false,
          dataSize: '2.1GB',
          uploadTime: '2024-02-01 14:20:00',
          isAnnotated: true,
          dataFormat: 'IMAGE',
          sampleCount: 89000,
          timeRange: '2021-2024年',
          updateFrequency: '实时'
        }
      ],
      'incremental': [
        {
          id: 'po-inc-001',
          name: '特殊作业环境增量数据',
          uploader: '检修班组C',
          isLearned: false,
          dataSize: '650MB',
          uploadTime: '2024-02-20 11:15:00',
          isAnnotated: false,
          dataFormat: 'VIDEO',
          sampleCount: 18000,
          timeRange: '2024年特殊工况',
          updateFrequency: '特殊作业'
        }
      ],
      'forgetting': [
        {
          id: 'po-forget-001',
          name: '历史作业遗忘评估数据',
          uploader: '质量监督部',
          isLearned: true,
          dataSize: '1.8GB',
          uploadTime: '2024-01-10 16:00:00',
          isAnnotated: true,
          dataFormat: 'IMAGE',
          sampleCount: 45000,
          timeRange: '2019-2021年',
          updateFrequency: '月度'
        }
      ],
      'quantization': [
        {
          id: 'po-quant-001',
          name: '人员识别量化校准数据',
          uploader: '算法优化组',
          isLearned: false,
          dataSize: '890MB',
          uploadTime: '2024-02-15 10:30:00',
          isAnnotated: true,
          dataFormat: 'IMAGE',
          sampleCount: 25000,
          timeRange: '代表性样本',
          updateFrequency: '版本更新'
        }
      ]
    },
    'equipment-defects': {
      'base': [
        {
          id: 'ed-base-001',
          name: '输电线路缺陷基础数据',
          uploader: '运检中心D',
          isLearned: true,
          dataSize: '4.5GB',
          uploadTime: '2024-01-20 08:45:00',
          isAnnotated: true,
          dataFormat: 'IMAGE',
          sampleCount: 198000,
          timeRange: '2020-2024年',
          updateFrequency: '每日'
        }
      ],
      'incremental': [
        {
          id: 'ed-inc-001',
          name: '新型缺陷增量数据',
          uploader: '技术研发部',
          isLearned: false,
          dataSize: '1.2GB',
          uploadTime: '2024-02-25 13:20:00',
          isAnnotated: false,
          dataFormat: 'IMAGE',
          sampleCount: 32000,
          timeRange: '2024年新发现',
          updateFrequency: '发现即更新'
        }
      ],
      'forgetting': [
        {
          id: 'ed-forget-001',
          name: '早期缺陷遗忘评估数据',
          uploader: '数据管理中心',
          isLearned: true,
          dataSize: '2.3GB',
          uploadTime: '2024-01-05 14:15:00',
          isAnnotated: true,
          dataFormat: 'IMAGE',
          sampleCount: 67000,
          timeRange: '2018-2020年',
          updateFrequency: '季度'
        }
      ],
      'quantization': [
        {
          id: 'ed-quant-001',
          name: '缺陷检测量化校准数据',
          uploader: '模型优化团队',
          isLearned: false,
          dataSize: '1.1GB',
          uploadTime: '2024-02-18 09:00:00',
          isAnnotated: true,
          dataFormat: 'IMAGE',
          sampleCount: 28000,
          timeRange: '典型缺陷样本',
          updateFrequency: '算法更新'
        }
      ]
    }
  });

  // 协同进化方法配置
  const collaborationMethods = [
    {
      id: 'knowledge_distillation',
      name: '知识协同',
      description: '通过教师模型向学生模型传递知识',
      icon: Brain,
      complexity: 'medium',
      efficiency: 'high'
    },
    {
      id: 'data_collaboration',
      name: '数据协同',
      description: '通过边侧样本归集，实现协同进化',
      icon: GitBranch,
      complexity: 'high',
      efficiency: 'medium'
    },
    {
      id: 'model_fusion',
      name: '模型协同',
      description: '多个模型权重融合获得更好性能',
      icon: Activity,
      complexity: 'low',
      efficiency: 'high'
    },
    {
      id: 'incremental_learning',
      name: '增量学习',
      description: '在新数据上持续学习而不遗忘旧知识',
      icon: TrendingUp,
      complexity: 'medium',
      efficiency: 'medium'
    }
  ];

  const calculateEstimation = () => {
    setIsCalculating(true);
    
    // 模拟计算过程
    setTimeout(() => {
      const results = {
        estimatedTime: '2.5小时',
        resourceUsage: {
          cpu: '65%',
          memory: '78%',
          gpu: '82%',
          bandwidth: '1.2GB/s'
        },
        expectedAccuracy: '94.2%',
        forgettingRate: '5.8%',
        costEstimate: '¥128.50',
        energyConsumption: '15.6 kWh'
      };
      setEstimationResults(results);
      setIsCalculating(false);
    }, 3000);
  };

  const handleCloudNodeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const nodeId = e.target.value;
    if (nodeId && !selectedNodes.includes(nodeId)) {
      setSelectedNodes(prev => [...prev, nodeId]);
    }
  };

  const handleEdgeNodeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const nodeId = e.target.value;
    if (nodeId && !selectedNodes.includes(nodeId)) {
      setSelectedNodes(prev => [...prev, nodeId]);
    }
  };

  const removeSelectedNode = (nodeId: string) => {
    setSelectedNodes(prev => prev.filter(id => id !== nodeId));
  };

  const getNodeInfo = (nodeId: string) => {
    const node = [...cloudNodes, ...edgeNodes].find(n => n.id === nodeId);
    return node;
  };

  const handleDatasetSelection = (datasetId: string) => {
    if (selectedDatasets.includes(datasetId)) {
      setSelectedDatasets(prev => prev.filter(id => id !== datasetId));
    } else {
      setSelectedDatasets(prev => [...prev, datasetId]);
    }
  };

  const removeSelectedDataset = (datasetId: string) => {
    setSelectedDatasets(prev => prev.filter(id => id !== datasetId));
  };

  const getCurrentDatasets = () => {
    if (!selectedScenario || !selectedDatasetType) return [];
    return datasetsData[selectedScenario]?.[selectedDatasetType] || [];
  };

  const getDatasetInfo = (datasetId: string) => {
    for (const scenario of Object.values(datasetsData)) {
      for (const type of Object.values(scenario)) {
        const dataset = type.find((d: any) => d.id === datasetId);
        if (dataset) return dataset;
      }
    }
    return null;
  };

  const handleStartTask = () => {
    setTaskStarted(true);
    // 这里可以添加启动任务的逻辑
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'online':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-600">
          <span className="w-1.5 h-1.5 bg-green-600 rounded-full mr-1.5"></span>
          在线
        </span>;
      case 'busy':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200">
          <span className="w-1.5 h-1.5 bg-yellow-600 rounded-full mr-1.5"></span>
          忙碌
        </span>;
      case 'offline':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-200">
          <span className="w-1.5 h-1.5 bg-red-600 rounded-full mr-1.5"></span>
          离线
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {status}
        </span>;
    }
  };

  return (
    <div className="space-y-4">
      {/* 紧凑的标题栏 */}
      <div className="flex items-center justify-between rounded-lg px-4 py-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900">协同进化配置</h1>
          <p className="text-sm text-gray-600 mt-0.5">云边协同训练配置与管理</p>
        </div>
        <Button variant="primary" size="sm">
          <Plus className="h-4 w-4 mr-1.5" />
          新建配置
        </Button>
      </div>

      {/* 紧凑的指标卡片 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">云端节点</div>
              <div className="text-2xl text-green-700 font-bold mt-1">
                {cloudNodes.filter(n => n.status === 'online').length}
              </div>
            </div>
            <Cloud className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">边缘节点</div>
              <div className="text-2xl text-green-700 font-bold mt-1">
                {edgeNodes.filter(n => n.status === 'online').length}
              </div>
            </div>
            <Server className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">数据集</div>
              <div className="text-2xl text-green-700 font-bold mt-1">
                {Object.values(datasetsData).reduce((sum, scenario) => 
                  sum + Object.values(scenario).reduce((typeSum, datasets) => typeSum + datasets.length, 0), 0
                )}
              </div>
            </div>
            <Database className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">进化方法</div>
              <div className="text-2xl text-green-700 font-bold mt-1">{collaborationMethods.length}</div>
            </div>
            <GitBranch className="h-6 w-6 text-green-600" />
          </div>
        </div>
      </div>

      {/* 协同进化方法选择 */}
      <div className="bg-white border border-gray-200 rounded-lg shadow-sm p-4">
        <h2 className="text-lg font-semibold text-gray-900 mb-3">选择协同进化方法</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
          {collaborationMethods.map((method) => {
            const IconComponent = method.icon;
            return (
              <div
                key={method.id}
                className={`p-3 rounded-lg border cursor-pointer transition-all ${
                  selectedMethod === method.id
                    ? 'border-green-600 bg-green-50'
                    : 'border-gray-200 hover:border-gray-300 bg-white'
                }`}
                onClick={() => setSelectedMethod(method.id)}
              >
                <div className="flex items-center mb-2">
                  <IconComponent className={`h-5 w-5 mr-2 ${
                    selectedMethod === method.id ? 'text-green-600' : 'text-gray-500'
                  }`} />
                  <h3 className="font-medium text-gray-900 text-sm">{method.name}</h3>
                </div>
                <p className="text-xs text-gray-600 mb-2">{method.description}</p>
                <div className="flex gap-2">
                  <span className={`text-xs px-2 py-0.5 rounded ${
                    method.complexity === 'high' ? 'bg-red-100 text-red-700' :
                    method.complexity === 'medium' ? 'bg-yellow-100 text-yellow-700' :
                    'bg-green-100 text-green-700'
                  }`}>
                    复杂度: {method.complexity === 'high' ? '高' : method.complexity === 'medium' ? '中' : '低'}
                  </span>
                  <span className={`text-xs px-2 py-0.5 rounded ${
                    method.efficiency === 'high' ? 'bg-green-100 text-green-700' :
                    'bg-yellow-100 text-yellow-700'
                  }`}>
                    效率: {method.efficiency === 'high' ? '高' : '中'}
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* 方法参数配置 */}
      {selectedMethod && (
        <div className="bg-white border border-gray-200 rounded-lg shadow-sm p-4">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">方法参数配置</h2>
          {selectedMethod === 'knowledge_distillation' && (
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">教师模型</label>
                  <select className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent">
                    <option>PowerVision-Workers v2.3.1</option>
                    <option>PowerNet-Defect v1.8.2</option>
                    <option>PowerGuard-Environment v3.1.0</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">学生模型架构</label>
                  <select className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent">
                    <option>MobileNet-v3</option>
                    <option>EfficientNet-B0</option>
                    <option>ResNet-18</option>
                  </select>
                </div>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">蒸馏温度</label>
                  <input type="number" defaultValue="4" min="1" max="10" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">损失权重</label>
                  <input type="number" defaultValue="0.7" min="0" max="1" step="0.1" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">学习率</label>
                  <input type="number" defaultValue="0.001" min="0.0001" max="0.1" step="0.0001" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
              </div>
            </div>
          )}

          {selectedMethod === 'data_collaboration' && (
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">聚合策略</label>
                  <select className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent">
                    <option>FedAvg</option>
                    <option>FedProx</option>
                    <option>FedNova</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">通信轮次</label>
                  <input type="number" defaultValue="100" min="10" max="1000" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">客户端参与率</label>
                  <input type="number" defaultValue="0.8" min="0.1" max="1.0" step="0.1" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">本地训练轮次</label>
                  <input type="number" defaultValue="5" min="1" max="20" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">学习率</label>
                  <input type="number" defaultValue="0.01" min="0.001" max="0.1" step="0.001" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
              </div>
            </div>
          )}

          {selectedMethod === 'model_fusion' && (
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">融合方式</label>
                  <select className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent">
                    <option>权重平均</option>
                    <option>加权平均</option>
                    <option>Fisher信息矩阵</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">融合层级</label>
                  <select className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent">
                    <option>全层融合</option>
                    <option>特征层融合</option>
                    <option>分类层融合</option>
                  </select>
                </div>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">融合权重</label>
                  <input type="number" defaultValue="0.5" min="0.1" max="0.9" step="0.1" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">正则化系数</label>
                  <input type="number" defaultValue="0.01" min="0.001" max="0.1" step="0.001" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">收敛阈值</label>
                  <input type="number" defaultValue="0.001" min="0.0001" max="0.01" step="0.0001" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
              </div>
            </div>
          )}

          {selectedMethod === 'incremental_learning' && (
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">增量策略</label>
                  <select className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent">
                    <option>Elastic Weight Consolidation</option>
                    <option>Learning without Forgetting</option>
                    <option>Progressive Neural Networks</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">记忆缓冲区大小</label>
                  <input type="number" defaultValue="1000" min="100" max="10000" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">遗忘惩罚系数</label>
                  <input type="number" defaultValue="1000" min="100" max="10000" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">学习率衰减</label>
                  <input type="number" defaultValue="0.95" min="0.8" max="0.99" step="0.01" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">任务数量</label>
                  <input type="number" defaultValue="5" min="2" max="20" className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent" />
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* 节点选择 */}
      <div className="bg-white border border-gray-200 rounded-lg shadow-sm p-4">
        <div className="flex items-center mb-4">
          <Server className="h-5 w-5 text-gray-600 mr-2" />
          <h2 className="text-lg font-semibold text-gray-900">节点选择与配置</h2>
        </div>
        
        {/* 云端节点选择 */}
        <div className="mb-4">
          <h4 className="text-md font-medium text-gray-800 mb-2">云端节点</h4>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <div>
              <select 
                className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent"
                onChange={handleCloudNodeChange}
                value=""
              >
                <option value="">选择云端节点</option>
                {cloudNodes.filter(node => node.status === 'online' && !selectedNodes.includes(node.id)).map(node => (
                  <option key={node.id} value={node.id}>
                    {node.name} - {node.location} ({node.gpu})
                  </option>
                ))}
              </select>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              {cloudNodes.filter(node => selectedNodes.includes(node.id)).map(node => (
                <div key={node.id} className="p-3 bg-green-50 border border-green-600 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <Cloud className="h-4 w-4 text-green-600" />
                    <button 
                      onClick={() => removeSelectedNode(node.id)}
                      className="text-green-600 hover:text-green-800"
                    >
                      ×
                    </button>
                  </div>
                  <div className="text-sm font-medium text-gray-900">{node.name}</div>
                  <div className="text-xs text-gray-600">{node.location}</div>
                  <div className="text-xs text-gray-600">{node.gpu}</div>
                  {getStatusBadge(node.status)}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* 边缘节点选择 */}
        <div>
          <h4 className="text-md font-medium text-gray-800 mb-2">边缘节点</h4>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <div>
              <select 
                className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent"
                onChange={handleEdgeNodeChange}
                value=""
              >
                <option value="">选择边缘节点</option>
                {edgeNodes.filter(node => node.status === 'online' && !selectedNodes.includes(node.id)).map(node => (
                  <option key={node.id} value={node.id}>
                    {node.name} - {node.location} ({node.gpu})
                  </option>
                ))}
              </select>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              {edgeNodes.filter(node => selectedNodes.includes(node.id)).map(node => (
                <div key={node.id} className="p-3 bg-green-50 border border-green-600 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <Server className="h-4 w-4 text-green-600" />
                    <button 
                      onClick={() => removeSelectedNode(node.id)}
                      className="text-green-600 hover:text-green-800"
                    >
                      ×
                    </button>
                  </div>
                  <div className="text-sm font-medium text-gray-900">{node.name}</div>
                  <div className="text-xs text-gray-600">{node.location}</div>
                  <div className="text-xs text-gray-600">{node.gpu}</div>
                  {getStatusBadge(node.status)}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* 数据集配置 */}
      <div className="bg-white border border-gray-200 rounded-lg shadow-sm p-4">
        <div className="flex items-center mb-4">
          <Database className="h-5 w-5 text-gray-600 mr-2" />
          <h2 className="text-lg font-semibold text-gray-900">数据集配置</h2>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">电力场景</label>
            <select 
              className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent"
              value={selectedScenario}
              onChange={(e) => setSelectedScenario(e.target.value)}
            >
              <option value="">选择场景</option>
              {powerScenarios.map(scenario => (
                <option key={scenario.id} value={scenario.id}>
                  {scenario.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">数据集类型</label>
            <select 
              className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-transparent"
              value={selectedDatasetType}
              onChange={(e) => setSelectedDatasetType(e.target.value)}
            >
              <option value="">选择类型</option>
              {datasetTypes.map(type => (
                <option key={type.id} value={type.id}>
                  {type.name}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* 数据集列表 */}
        {getCurrentDatasets().length > 0 && (
          <div className="mb-4">
            <h4 className="text-md font-medium text-gray-800 mb-2">可用数据集</h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              {getCurrentDatasets().map((dataset: any) => (
                <div 
                  key={dataset.id}
                  className={`p-3 border rounded-lg cursor-pointer transition-all ${
                    selectedDatasets.includes(dataset.id)
                      ? 'border-green-600 bg-green-50'
                      : 'border-gray-200 hover:border-gray-300 bg-white'
                  }`}
                  onClick={() => handleDatasetSelection(dataset.id)}
                >
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex-1">
                      <h5 className="text-sm font-medium text-gray-900">{dataset.name}</h5>
                      <p className="text-xs text-gray-600 mt-1">上传者: {dataset.uploader}</p>
                    </div>
                    <div className="flex flex-col items-end">
                      <span className={`text-xs px-2 py-0.5 rounded ${
                        dataset.isLearned ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'
                      }`}>
                        {dataset.isLearned ? '已学习' : '未学习'}
                      </span>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-2 text-xs text-gray-600">
                    <div>大小: {dataset.dataSize}</div>
                    <div>样本: {dataset.sampleCount.toLocaleString()}</div>
                    <div>格式: {dataset.dataFormat}</div>
                    <div>标注: {dataset.isAnnotated ? '是' : '否'}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 已选择的数据集 */}
        {selectedDatasets.length > 0 && (
          <div>
            <h4 className="text-md font-medium text-gray-800 mb-2">已选择数据集</h4>
            <div className="space-y-2">
              {selectedDatasets.map(datasetId => {
                const dataset = getDatasetInfo(datasetId);
                if (!dataset) return null;
                return (
                  <div key={datasetId} className="flex items-center justify-between p-2 bg-green-50 border border-green-600 rounded">
                    <div className="flex items-center">
                      <Database className="h-4 w-4 text-green-600 mr-2" />
                      <span className="text-sm font-medium text-gray-900">{dataset.name}</span>
                      <span className="text-xs text-gray-600 ml-2">({dataset.dataSize})</span>
                    </div>
                    <button 
                      onClick={() => removeSelectedDataset(datasetId)}
                      className="text-green-600 hover:text-green-800"
                    >
                      ×
                    </button>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* 资源预估 */}
      <div className="bg-white border border-gray-200 rounded-lg shadow-sm p-4">
        <div className="flex items-center mb-4">
          <BarChart3 className="h-5 w-5 text-gray-600 mr-2" />
          <h2 className="text-lg font-semibold text-gray-900">资源估算与预测</h2>
        </div>
        
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-600">
              {selectedNodes.length > 0 && selectedDatasets.length > 0 
                ? `已选择 ${selectedNodes.length} 个节点和 ${selectedDatasets.length} 个数据集`
                : '请先选择节点和数据集'
              }
            </div>
            <Button 
              variant="primary" 
              size="sm"
              onClick={calculateEstimation}
              disabled={isCalculating || selectedNodes.length === 0 || selectedDatasets.length === 0}
            >
              {isCalculating ? (
                <>
                  <Activity className="h-4 w-4 mr-1.5 animate-spin" />
                  计算中...
                </>
              ) : (
                <>
                  <BarChart3 className="h-4 w-4 mr-1.5" />
                  开始估算
                </>
              )}
            </Button>
          </div>

          {isCalculating && (
            <div className="text-center py-6">
              <Activity className="h-6 w-6 text-green-600 mx-auto mb-3 animate-spin" />
              <p className="text-sm text-gray-600">正在分析配置并计算资源需求...</p>
            </div>
          )}

          {estimationResults && (
            <div className="space-y-3">
              {/* 核心指标 - 三列布局 */}
              <div className="grid grid-cols-3 gap-3">
                <div className="bg-gradient-to-br from-green-50 to-green-100 border border-green-200 rounded-lg p-3">
                  <div className="flex items-center justify-between mb-1">
                    <Clock className="h-4 w-4 text-green-600" />
                    <span className="text-xs text-green-700 font-medium">预计时间</span>
                  </div>
                  <p className="text-xl font-bold text-green-900">{estimationResults.estimatedTime}</p>
                </div>
                
                <div className="bg-gradient-to-br from-blue-50 to-blue-100 border border-blue-200 rounded-lg p-3">
                  <div className="flex items-center justify-between mb-1">
                    <CheckCircle className="h-4 w-4 text-blue-600" />
                    <span className="text-xs text-blue-700 font-medium">预期准确率</span>
                  </div>
                  <p className="text-xl font-bold text-blue-900">{estimationResults.expectedAccuracy}</p>
                </div>
                
                <div className="bg-gradient-to-br from-orange-50 to-orange-100 border border-orange-200 rounded-lg p-3">
                  <div className="flex items-center justify-between mb-1">
                    <AlertCircle className="h-4 w-4 text-orange-600" />
                    <span className="text-xs text-orange-700 font-medium">遗忘率</span>
                  </div>
                  <p className="text-xl font-bold text-orange-900">{estimationResults.forgettingRate}</p>
                </div>
              </div>

              {/* 详细信息 - 两列布局 */}
              <div className="grid grid-cols-2 gap-3">
                <div className="bg-white border border-gray-200 rounded-lg p-3">
                  <div className="flex items-center mb-2">
                    <Activity className="h-4 w-4 text-gray-600 mr-2" />
                    <h4 className="text-sm font-semibold text-gray-900">资源使用率</h4>
                  </div>
                  <div className="space-y-2">
                    {Object.entries(estimationResults.resourceUsage).map(([resource, usage]) => (
                      <div key={resource} className="flex items-center justify-between">
                        <span className="text-xs text-gray-600 w-12">
                          {resource === 'cpu' ? 'CPU' : resource === 'memory' ? '内存' : resource === 'gpu' ? 'GPU' : '带宽'}
                        </span>
                        <div className="flex-1 mx-2">
                          <div className="w-full bg-gray-200 rounded-full h-1.5">
                            <div 
                              className="bg-green-600 h-1.5 rounded-full transition-all duration-300"
                              style={{ width: String(usage) }}
                            ></div>
                          </div>
                        </div>
                        <span className="text-xs font-medium text-gray-900 w-12 text-right">{String(usage)}</span>
                      </div>
                    ))}
                  </div>
                </div>
                
                <div className="bg-white border border-gray-200 rounded-lg p-3">
                  <div className="flex items-center mb-2">
                    <Zap className="h-4 w-4 text-gray-600 mr-2" />
                    <h4 className="text-sm font-semibold text-gray-900">成本与能耗</h4>
                  </div>
                  <div className="space-y-2">
                    <div className="flex justify-between items-center py-1">
                      <span className="text-xs text-gray-600">预估成本</span>
                      <span className="text-sm font-semibold text-gray-900">{estimationResults.costEstimate}</span>
                    </div>
                    <div className="w-full h-px bg-gray-200"></div>
                    <div className="flex justify-between items-center py-1">
                      <span className="text-xs text-gray-600">能耗估算</span>
                      <span className="text-sm font-semibold text-gray-900">{estimationResults.energyConsumption}</span>
                    </div>
                  </div>
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-center pt-2">
                <Button 
                  variant="primary" 
                  onClick={handleStartTask}
                  disabled={taskStarted}
                  className="px-6"
                >
                  {taskStarted ? (
                    <>
                      <CheckCircle className="h-4 w-4 mr-2" />
                      任务已启动
                    </>
                  ) : (
                    <>
                      <Play className="h-4 w-4 mr-2" />
                      启动协同进化任务
                    </>
                  )}
                </Button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
} 